///////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2010 Chris Colinsky
// All Rights Reserved
//
// version	0.5
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

package sugarcookie.components.videoPlayer {
	import flash.utils.describeType;
	
	import sugarcookie.components.videoPlayer.vo.PlayListItem;
	import sugarcookie.error.ApplicationError;
	import sugarcookie.utils.ArrayUtil;
	
	public class MediaManager {
		private static var _inst:MediaManager;
		private static var _media:Array = [];
		private static var _basePath:String = "";
		
		public static function set basePath(value:String):void { _basePath = value; }
		
		public static function addMedia(data:*):void {
			var type:String = describeType(data).@name;
			switch(type) {
				case "Array":
					_media = _media.concat(data);
					break;
				case "Object":
					_media.push(data);
					break;
			}
		}
		
		public static function createPlayList(...args):PlayList {
			var list:PlayList = new PlayList();
			var ids:Array = args as Array;
			var len:int = ids.length;
			
			for (var i:int=0;i<len;i++) {
				var type:String = describeType(ids[i]).@name;
				switch(type) {
					case "String":
						process([ ids[i] ]);
						break;
					case "Array":
						process(ids[i]);
						break;
				}
			}
			
			function process(_items:Array):void {
				var len:int = _items.length;
				for (var i:int=0;i<len;i++) {
					try {
						var data:Object = getMediaObjectById(_items[i]);
						var item:PlayListItem = new PlayListItem(_basePath + data.uri);
						if (data.mediaType) item.mediaType = data.mediaType;
						if (data.label) item.label = data.label;
						if (data.volume) item.volume = data.volume; 
						list.addToQueue(item);
					} catch (e:Error) {
						continue;
					}
				}
			}
			
			return list;
		}
		
		private static function getMediaObjectById(id:String):Object {
			var index:int = ArrayUtil.indexOfByPropValue(_media,"id",id);
			if (index<0) throw new ApplicationError("Id was not found in media library.");
			else return _media[index];
		}
	}
}